import TableHead from '@/components/quarterly-account-table/table-head.vue'
import ReportPerson from '@/components/quarterly-account-table/report-person.vue'
import { uuid } from '@/utils'
import { loadDescription } from '@/api/descriptionManagement'
import { TABLE_FIELD_QUARTER, TABLE_FIELD_YEAR, ENTERPRISE_BASIC_INFORMATION_TABLE_ID, TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT } from '@/config'

export default {
  components: {
    TableHead,
    ReportPerson
  },
  props: {
    // 企业ID
    enterpriseId: {
      type: String,
      required: true,
    },
    // 企业名称
    enterpriseName: String,
    // 年份
    year: {
      type: [String, Number],
      required: true,
    },
    // 季度
    quarter: {
      type: [String, Number],
      required: true,
    },
    // 表ID
    tId: {
      type: Number,
      required: true,
    },
    // 表名称
    name: {
      type: String,
      required: true,
    },
    // 表数据项
    columns: {
      type: Array,
      required: true,
    },
    // 政府端
    isGovernment: Boolean,
    readonly: Boolean,
    showLineNumber: {
      type: Boolean,
      default: true,
    }
  },
  data () {
    return {
      // 点击单元格后，正在输入的input索引
      inputIndex: -1,
      rowIndex: -1,
      /**
       * 报表数据格式
       * @types {
       *    uuid: string,
       *    data: {
       *      value: string;
       *      calculable: boolean;
       *      readonly: boolean;
       *      background: boolean;
       *    }[]
       * }[]
       */
      lists: [],

      // context menu box
      left: 0,
      top: 0,

      // 填报说明
      tableDescription: '',

      // 防止自动保存发生在请求数据之前
      loading: true,
    }
  },
  computed: {
    title () {
      // 年度
      if (Number(this.quarter) === 5) {
        return `${this.year}年度${this.name}`
      }

      return `${this.year}年第${this.quarter}季度${this.name}`
    },
    fromGovernmentSide () {
      return this.isGovernment && this.readonly === true
    },
    // 多级表头转一级表头
    flattenColumns () {
      const columns = this.columns
      const getItems = (arr) => {
        const result = [];
        (function callback (arr) {
          for (let i = 0; i < arr.length; i++) {
            const { children, ...rest } = arr[i]
            if (children && children.length > 0) {
              callback(children)
            } else if (!rest.hidden) {
              result.push({ ...rest })
            }
          }
        })(arr)
        return result
      }
      return getItems(columns)
    },
    // 填报人相关信息
    informant () {
      const lists = this.lists
      const item = lists[0] && lists[0].informant
      if (!item) {
        return {}
      }
      return {
        principal: item.personInCharge || '',
        informant: item.informer || '',
        telephone: item.telephone || '',
        date: item.fillInDate || '',
      }
    },
  },
  mounted () {
    this.getDescription(this.tId)
    const res = this.initLists()
    if (res && res.finally) {
      res.finally(() => {
        this.loading = false
      })
    } else {
      this.loading = false
    }
  },
  methods: {
    getPrevLists (params) {
      if (
        this.tId === ENTERPRISE_BASIC_INFORMATION_TABLE_ID ||
        this.tId === TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT
      ) {
        // 企业基本情况表, 单位产品综合能耗情况表点击加载上期数据要特殊处理 （loadOnClickPrevButton）
        // “本期”填充“上期”数据
        return this.initLists(params, true);
      }
      return this.initLists(params)
    },
    refresh () {
      this.initLists()
    },
    _initLists (l, min) {
      min = min || 2
      if (l < min) {
        let rest = []
        if (this.transfer) {
          rest = this.transfer(Array(min - l).fill({}))
        } else {
          const columns = this.flattenColumns
          rest = Array(min - l).fill(1).map(() => ({
            uuid: uuid(),
            data: columns.map(v => ({
              key: v.prop,
              value: '',
              editable: !this.readonly
            }))
          }))
        }
        this.lists = this.lists.concat(rest)
      }
    },
    // 暴露给使用者的获取填报人相关信息
    getInformer () {
      return this.$refs.reportPerson && this.$refs.reportPerson.getData()
    },
    // 暴露给使用者的获取报表数据的方法
    // @return [{prop1: string, prop2: string, ...}]
    getData () {
      const props = this.flattenColumns.map(v => v.prop)
      const isNotEmpty = (array) => array.some(
        v => v !== TABLE_FIELD_QUARTER &&
          v !== TABLE_FIELD_YEAR && v !== 'state' &&
          v !== ''
      )

      // 二维数组 [string[], string[], ...]
      const lists = this.lists.filter(v => isNotEmpty(v.data))
      return lists.map((v, i) => {
        v = v.data
        const obj = {}
        props.forEach((prop, index) => {
          obj[prop] = typeof this.getCalc === 'function'
            ? String(this.getCalc(i, prop, v[index].value) || '')
            : (v[index].value || '')
        })
        obj[TABLE_FIELD_YEAR] = String(this.year)
        obj[TABLE_FIELD_QUARTER] = String(this.quarter)
        return obj
      })
    },
    // 单击单元格（input框）
    clickHandler (evt, rowIndex) {
      evt.target.select()
      this.inputIndex = Number(evt.target.dataset.inputIndex)
      this.rowIndex = rowIndex

      this.visible = false
    },
    // 给每个input添加索引
    initInputIndex () {
      const inputs = document.querySelectorAll('.input-cell input')
      inputs.forEach((input, index) => {
        input.dataset.inputIndex = index + ''
      })
    },
    // 获取填报说明
    async getDescription (tId) {
      const { data } = await loadDescription(tId)
      const { descriptionContent } = data || {}
      this.tableDescription = descriptionContent
    }
  }
}
